﻿using System;
using System.Windows;

namespace Silverlight.InputCtrl
{
    public class RangeValidator : ValidatorBase
    {


        public double Min
        {
            get { return (double)GetValue(MinProperty); }
            set { SetValue(MinProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Min.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MinProperty =
            DependencyProperty.Register("Min", typeof(double), typeof(RangeValidator), new PropertyMetadata(Double.MinValue));

        public double Max
        {
            get { return (double)GetValue(MaxProperty); }
            set { SetValue(MaxProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Max.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MaxProperty =
            DependencyProperty.Register("Max", typeof(double), typeof(RangeValidator), new PropertyMetadata(double.MaxValue));

        public override bool Validate()
        {
            base.IsValidResult = true;
            FrameworkElement _elemValidate = base.ElementValidator;
            if (_elemValidate != null && Enabled)
            {
                string value = "";
                value = ValidatorCommon.GetValueText(_elemValidate,base.PropertyToValidate);
                if (!String.IsNullOrEmpty(value))
                {
                    value = value.Trim();
                    base.IsValidResult = false;
                    double dvalue;
                    if (double.TryParse(value, out dvalue))
                    {
                        base.IsValidResult = (dvalue >= Min && dvalue <= Max);
                    }
                }
            }
            return base.IsValidResult;
        }
    }
}
